#include "StdAfx.h"
#include "BoostFileSystem.h"

#include <boost/filesystem.hpp>

BoostFileSystem::BoostFileSystem(const std::string& rootPath)
	: m_rootPath(rootPath)
{}

void BoostFileSystem::rename(const std::string& oldPath, const std::string& newPath, ftp::FileSystemError* error)
{
	boost::filesystem::path rootPath(m_rootPath);
	boost::system::error_code errorCode;
	boost::filesystem::rename(rootPath / oldPath, rootPath / newPath, errorCode);

	*error = errorCode ? ftp::kFileOrPathDoesNotExist : ftp::kSuccess;
}

void BoostFileSystem::createDirectory(const std::string& dir, ftp::FileSystemError* error)
{
	boost::filesystem::path rootPath(m_rootPath);
	boost::system::error_code errorCode;
	boost::filesystem::create_directory(rootPath / dir, errorCode);

	*error = errorCode ? ftp::kFileOrPathDoesNotExist : ftp::kSuccess;
}

void BoostFileSystem::removeDirectory(const std::string& dir, ftp::FileSystemError* error)
{
	boost::filesystem::path rootPath(m_rootPath);
	if (!boost::filesystem::exists(rootPath / dir))
	{
		*error = ftp::kFileOrPathDoesNotExist;
		return;
	}

	boost::system::error_code errorCode;
	boost::filesystem::remove_all(rootPath / dir, errorCode);

	*error = errorCode ? ftp::kNoPermissions : ftp::kSuccess;
}

bool BoostFileSystem::doesDirectoryExist(const std::string& dir)
{
	boost::filesystem::path rootPath(m_rootPath);
	return boost::filesystem::exists(rootPath / dir);
}

void BoostFileSystem::readDirectory(const std::string& dir, std::vector<std::string>* fileNames, ftp::FileSystemError* error)
{
	fileNames->clear();

	boost::filesystem::path rootPath(m_rootPath);
	if (!boost::filesystem::exists(rootPath / dir))
	{
		*error = ftp::kFileOrPathDoesNotExist;
		return;
	}

	boost::filesystem::directory_iterator it(rootPath / dir);
	boost::filesystem::directory_iterator end;

	for (; it != end; ++it)
	{
		fileNames->push_back(it->path().filename().string());
	}

	*error = ftp::kSuccess;
}

std::auto_ptr<ftp::File> BoostFileSystem::openFile(const std::string& dir, ftp::FileSystemError* error) 
{
	return std::auto_ptr<ftp::File>(nullptr);
}
